
export const format =function(value,format){
    let first = format.substr(0,1);
    let result ='';
    switch(first){
        case 'y':
        case 'M':
        case 'm':
        case 'h':
        case 'd':
        case 's':
        case 'S':
        case 'q':
        case 'w':
        case 'W':
            result = dateFormat(value,format);
            break;
        case '0':
        case '#':
            result = numFormat(value,format);
            break;
        case '整':
            result =formatBigRMB(value);
            break;

    }
    //return numFormat(value,format);
    return result;
};

// 单个日期格式化
export const dateFormat = function(theDate, fmt) {
    if(!(theDate instanceof Date))
        return '';
	let o = {
		"M+": theDate.getMonth() + 1, //月份
		"d+": theDate.getDate(), //日
		"h+": theDate.getHours(), //小时
        //"H+": get12Hours(theDate),
		"m+": theDate.getMinutes(), //分
		"s+": theDate.getSeconds(), //秒
		"q": Math.floor((theDate.getMonth() + 3) / 3), //季度
		"S": theDate.getMilliseconds(),
        "^W$": getWeekNum(theDate) //iso 周
	};
	// 周
    if(/y+\S*w+/.test(fmt)){
	    let w = getWeekNum(theDate);
	    if(/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1,w.substr(0,4));

	    if(/(w+)/.test(fmt))
             fmt = fmt.replace(RegExp.$1,zeroRetain(w.substr(5,2),RegExp.$1.length));
    }
    else{
        if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (theDate.getFullYear() + "").substr(4 - RegExp.$1.length));
        if(/(H+)/.test(fmt)) fmt = fmt.replace(RegExp.$1,get12Hours(theDate));
        for(let k in o){
            if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }

    }
	return fmt;
};

/*所有非0项都保留，0 的保留 根据长度，是否保留或者补全前面的0*/
export const zeroRetain=function(data,length){
    let nonZero = data.replace(/\b(0+)/gi,"");
    //非 零 的长度 > length
    if(nonZero.length>= length)
        return nonZero;
    else
        return new Array(length - (data + '').length + 1).join('0') + data;
};

export const get12Hours=function(theDate){
    let h = theDate.getHours();
    if(h>=1 && h<5)
        return '凌晨'+h;
    if(h>=5 && h<7)
        return '清晨'+h;
    if(h>=7 && h<9)
        return '早上'+h;
    if(h>=9 && h<11)
        return '上午'+h;
    if(h>=11 && h<13)
        return '中午'+h;
    if(h>=13 && h<17)
        return '下午'+(h-12);
    if(h>=17 && h<19)
        return '傍晚'+(h-12);
    if(h>=19 && h<=22)
        return '晚上'+(h-12);
    if(h==23)
        return '半夜'+(h-12);
    if(h==0)
        return '半夜'+h;
}

// iso8601 2021W01
export const getWeekNum=function(theDate){
    let result ='';
    let year = new Date(theDate).getFullYear();
    //第一月第四天，一定在本年第一周中
    let xDate1 = new Date(year+'-01-04');
    let bDate = new Date(xDate1.valueOf()-(xDate1.getDay()==0?6:xDate1.getDay()-1)*86400000);
    //12-28 一定在本年最后一周中
    let xDate2 = new Date(year+'-12-28');
    let eDate = new Date(xDate2.valueOf()+(xDate2.getDay()==0?0:7-xDate2.getDay())*86400000);
    if(new Date(theDate)<bDate)
        result = getWeekNum(year-1+'-12-28');
    else if(new Date(theDate)>eDate)
        result = getWeekNum(year-0+1+'-01-04');
    else
        result = year+'W'+fillZero(2,parseInt((new Date(theDate).valueOf()- bDate.valueOf())/86400000/7)+1);
    return result;
};
//月份 相加
export const monthAdd=function(month,span){
    // month 202001
    let monthOfNum = parseInt(month.replace('-',''))
    let allM = Math.floor(monthOfNum/100)*12+monthOfNum%100+span;
    let y = Math.floor(allM/12) ;
    var m = allM%12
    if (m ==0) {
        y = y-1;
        m = 12;
    }
    return y+'-'+ (m<10?'0':'')+m;
};

//周数相加
export const weekAdd=function(week,span){
    let firstDate = getFirstDateOfWeek(week);
    return dateFormat(new Date(new Date(firstDate).valueOf()+ span*7*86400000),'yyyy-ww')
};

//一年有多少周 ISO8601:2000 标准
export const getWeeksOfYear=function(year){
    let xDate = new Date(year+'-01-04');
    let eDate = new Date(year+'-12-28');
    let bDate = xDate.valueOf()-(xDate.getDay()==0?7:xDate.getDay())*86400000;
    return Math.ceil((eDate.valueOf()- bDate)/86400000/7);
}

//周第一天
export const getFirstDateOfWeek=function(week){
    let ordinal = week.substr(5,2)-1;
    let year = week.substr(0,4);
    let xDate = new Date(year+'-01-04');
    let bDate = new Date(xDate.valueOf()-(xDate.getDay()==0?6:xDate.getDay()-1)*86400000);
    return dateFormat(new Date(bDate.valueOf()+ordinal*7*86400000),'yyyy-MM-dd');
};
//周最后一天
export const getLastDateOfWeek =function(week){
    let ordinal = week.substr(5,2)-1;
    let year = week.substr(0,4);
    let xDate = new Date(year+'-01-04');
    let bDate = new Date(xDate.valueOf()-(xDate.getDay()==0?6:xDate.getDay()-1)*86400000);
    return dateFormat(new Date(bDate.valueOf()+ordinal*7*86400000+6*86400000),'yyyy-MM-dd');
};

//月最后一天
export const getLastDateOfMonth = function(month){
    let nextMonth = monthAdd(month,1);
    return dateFormat(new Date(new Date(nextMonth+'-01')-86400000),'yyyy-MM-dd');
};

export const getRecentDay = function(offset,day){
    //console.log((day || new Date()).valueOf()+offset*86400000);
    return new Date((day||new Date()).valueOf()+offset*86400000);
};

export const fillZero = function(length,string) {
    return new Array(length - (string + '').length + 1).join('0') + string;
} //输出006


export const numFormat = function(value, format) {
	//
	let formatValue = '';
	let headChar = ''
	let afterChar = '';
	let scale = 0;
    let val = value-0;
	if(isNaN(val))
	    return '';

	if(format == '¥元') {
		return '¥' + formatBigRMB(value);
	}

	if(format == '元') {
		return formatBigRMB(value);
	}

	let scaleReg = /\.0+/g
	//解析 format
	if(format[0] == '¥') {
		headChar = '¥';
	}

	if(format.indexOf('%') > -1) {
		val = val * 100;
		afterChar = '%';
	}

	let m = format.match(/\.0+/g);
	if(!!m) {
		scale = m[0].length - 1;
		val = val.toFixed(scale);
	} else {
		val = val.toFixed(0);
	}

	if(format.indexOf('#') > -1) {
		let reg = /(\d)(?=((\d{3})+$))/g;
		let sInt = (val + '').split('.')[0];
		sInt = sInt.replace(reg, '$1,');
		if((val + '').split('.').length > 1)
			val = sInt + '.' + (val + '').split('.')[1];
		else
			val = sInt;
	}
	return headChar + val + afterChar;
}

export const formatBigRMB = function(money) {

	/** 数字金额大写转换(可以处理整数,小数,负数) */
	let fraction = ['角', '分'];
	let digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
	let unit = [
		['元', '万', '亿'],
		['', '拾', '佰', '仟']
	];
	let head = money < 0 ? '欠' : '';
	let n = Math.abs(money);

	let s = '';

	for(let i = 0; i < fraction.length; i++) {
		s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
	}
	s = s || '整';
	n = Math.floor(n);

	for(let i = 0; i < unit[0].length && n > 0; i++) {
		let p = '';
		for(let j = 0; j < unit[1].length && n > 0; j++) {
			p = digit[n % 10] + unit[1][j] + p;
			n = Math.floor(n / 10);
		}
		s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
	}
	return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');

}

export const getBrowser=function(){
    let Sys = {};
    let ua = navigator.userAgent.toLowerCase();
    let s;
    (s = ua.indexOf('edge') !== - 1 ? Sys.edge = 'edge' : ua.match(/rv:([\d.]+)\) like gecko/)) ? Sys.ie = s[1]:
        (s = ua.match(/msie ([\d.]+)/)) ? Sys.ie = s[1] :
            (s = ua.match(/firefox\/([\d.]+)/)) ? Sys.firefox = s[1] :
                (s = ua.match(/chrome\/([\d.]+)/)) ? Sys.chrome = s[1] :
                    (s = ua.match(/opera.([\d.]+)/)) ? Sys.opera = s[1] :
                        (s = ua.match(/version\/([\d.]+).*safari/)) ? Sys.safari = s[1] : 0;
    return Sys;
};

export const getDownloadUrl =function (fileData,fileType) {
    let _utf = "\uFEFF"; // 为了使Excel以utf-8的编码模式，同时也是解决中文乱码的问题
    let data = fileData;
    if (window.Blob && window.URL && window.URL.createObjectURL) {
         data = new Blob([_utf + fileData], {
            type: fileType?fileType:'text/plain'
        });
        return URL.createObjectURL(data);
    }
}

export const saveAsXmlXls = function(fileName,fileData){
    let bw = getBrowser();
    if(!bw['edge'] || !bw['ie']) {
        let alink = document.createElement("a");
        alink.id = "linkDwnldLink";
        alink.href = getDownloadUrl(fileData);
        document.body.appendChild(alink);
        let linkDom = document.getElementById('linkDwnldLink');
        linkDom.setAttribute('download', fileName);
        linkDom.click();
        document.body.removeChild(linkDom);
    }
    else if(bw['ie'] >= 10 || bw['edge'] == 'edge') {
        let _utf = "\uFEFF";
        let _xmlData = new Blob([_utf + fileData], {
            type: 'text/plain'
        });
        navigator.msSaveBlob(_xmlData, fileName);
    }
}

export const saveAsCsv = function(fileName,fileData){
    let bw = getBrowser();
    if(!bw['edge'] || !bw['ie']) {
        let alink = document.createElement("a");
        alink.id = "linkDwnldLink";
        alink.href = getDownloadUrl(fileData,'text/csv');
        document.body.appendChild(alink);
        let linkDom = document.getElementById('linkDwnldLink');
        linkDom.setAttribute('download', fileName);
        linkDom.click();
        document.body.removeChild(linkDom);
    }
    else if(bw['ie'] >= 10 || bw['edge'] == 'edge') {
        let _utf = "\uFEFF";
        let _csvData = new Blob([_utf + fileData], {
            type: 'text/csv'
        });
        navigator.msSaveBlob(_csvData, fileName);
    }
}

export const jsonToCsv=function(jd){
    let row = '';
    let csv = '';
    //col
    for(let key in jd[0]){
        if(!(key.charAt(0) =='_' || (typeof jd[0][key] =='object')))
             row += '"'+key+'",'
    }
    row = row.slice(0, -1);
    csv  = row +'\r\n';
    //data
    jd.forEach(data =>{
        row ='';
        for(let key in data){
            if(!(key.charAt(0) =='_' || (typeof data[key] =='object')))
                row += '"'+data[key]+'",'
        }
        row = row.slice(0, -1);
        csv += row +'\r\n';
    });
    return csv;
}

/*
* */
export const replaceByObj = function(str,obj){
    let s =str;
    for(let k of Object.keys(obj)){
        let reg = new RegExp('{{'+k+'}}' , 'g');
        s = s.replace(reg,obj[k])
    }
    return s;
}

export const overrideObj=function(obj1,obj2){
    for(let key in obj1) {
        obj1[key] = obj2[key];
    }
};

export const isImg=function(name){
    return name?(name.indexOf('.')>-1?true:false):false;
}

export const getValueForFilter = function(val){
    if(typeof  val == 'number')
        return val;
    else
        return  val||'(空白)';
}

/*
*  null undefinded  统一转换 成  '';
* */
export const  emptyVal=function(val){
    if(typeof  val == 'number')
        return val;
    else
        return val?val:'';
}

//返回第一匹配的   多多比较
export const getFisrtMatchOfMultiples=function(srcs,tgts){
    let result='';
    let srcArray = (typeof srcs =='string')?srcs.split(','):srcs;
    let tgtArray = (typeof tgts =='string')?tgts.split(','):tgts;
    for(let s of srcArray){
        if (tgtArray.includes(s)){
            result = s;
            break;
        }
    }
    return result;
}

//是否匹配  多多比较 其中有一个匹配就返回成功
export const isMatchOfMultiples=function(srcs,tgts){
    let result =false;
    let srcArray = (typeof srcs =='string')?srcs.split(','):srcs;
    let tgtArray = (typeof tgts =='string')?tgts.split(','):tgts;
    for(let s of srcArray){
        if (tgtArray.includes(s)){
            result = true;
            break;
        }
    }
    return result;
}

export const getCellSpanByDom=function(td){
    let colspan = td.getAttribute('colspan');
    let rowspan =  td.getAttribute('rowspan');
    colspan =colspan?colspan-0:1;
    rowspan = rowspan?rowspan-0:1;
    return {colspan,rowspan};
}

export const ifNull = function(obj,val){
    return (obj ==null || obj =='' || obj ==undefined)?val:obj;
}

/*for 原生js */

//判断样式是否存在
export const hasClass=function (ele, cls) {
    return ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}
//为指定的dom元素添加样式
export const addClass=function(ele, cls) {
    if (!hasClass(ele, cls)) ele.className += " " + cls;
}
//删除指定dom元素的样式
export const removeClass= function(ele, cls) {
    if (hasClass(ele, cls)) {
        let reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
        ele.className = ele.className.replace(reg, " ");
    }
}
//如果存在(不存在)，就删除(添加)一个样式
export const toggleClass= function(ele,cls){
    if(hasClass(ele,cls)){
        removeClass(ele, cls);
    }else{
        addClass(ele, cls);
    }
}

// 移除子串链 里面的字串
export const removeSubs=function(strings,subs){
    let strArray = strings && strings.length>1?strings.split(','):[];
    let subArray = subs && subs.length>1? subs.split(','):[];
    let array =[];
    strArray.forEach(data =>{
        if (!subArray.includes(data))
            array.push(data);
    });
    return array.join(',');
}

//增加子串链 要求去重
export const addSubs =function(strings,subs){
    let strArray = strings && strings.length>1?strings.split(','):[];
    let subArray = subs && subs.length>1? subs.split(','):[];
    let array =[];
    let set = new Set(strArray);
    subArray.forEach(data => set.add(data));
    return Array.from(set).join(',');
}

// 自适应格式文件大小
export const formatFileSize =function(fileSize) {
    if (fileSize < 1024) {
        return fileSize + 'B';
    } else if (fileSize < (1024*1024)) {
        var temp = fileSize / 1024;
        temp = temp.toFixed(2);
        return temp + 'KB';
    } else if (fileSize < (1024*1024*1024)) {
        var temp = fileSize / (1024*1024);
        temp = temp.toFixed(2);
        return temp + 'MB';
    } else {
        var temp = fileSize / (1024*1024*1024);
        temp = temp.toFixed(2);
        return temp + 'GB';
    }
}

//比较仅限于互有的属性
export const compareJSON = function (JSON1,JSON2){
    if ((JSON1 && typeof JSON1 === "object") && ((JSON2 && typeof JSON2 === "object"))) {
        for (let key in JSON1) {
            if (JSON1.hasOwnProperty(key) && JSON2.hasOwnProperty(key)) {
                if(JSON1[key] && JSON2[key]){
                    if (JSON1[key].constructor == Array && JSON2[key].constructor == Array)//如果属性是数组
                    {
                        if (!compareArray(JSON1[key], JSON2[key])) {
                            return false;
                        };
                    }
                    else if (typeof JSON1[key] === "string" && typeof JSON2[key] === "string")//纯属性
                    {
                        if (JSON1[key] !== JSON2[key]) {
                            return false;
                        }
                    }
                    else if (typeof JSON1[key] === "number" && typeof JSON2[key] === "number")//纯属性
                    {
                        if (JSON1[key] !== JSON2[key]) {
                            return false;
                        }
                    }
                    else if (typeof JSON1[key] === "boolean" && typeof JSON2[key] === "boolean")//纯属性
                    {
                        if (JSON1[key] !== JSON2[key]) {
                            return false;
                        }
                    }
                    else if (typeof JSON1[key] === "object" && typeof JSON2[key] === "object")//属性是对象
                    {
                        if (!compareJSON(JSON1[key], JSON2[key])) {
                            return false;
                        };
                    }
                    else{

                    }

                }
                else{
                    // 全部 为 null 则相等
                    if ((!JSON1[key]) != (!JSON2[key]))
                        return false;
                }
            }
        }
    }
    return true;
}

export const compareArray = function(array1,array2){
 if ((array1 && typeof array1 === "object"
                && array1.constructor === Array)
            && (array2 && typeof array2 === "object" && array2.constructor === Array)) {
            if (array1.length == array2.length) {
                for (let i = 0; i < array1.length; i++) {
                    let compareResult = compareJSON(array1[i], array2[i]);
                    if (!compareResult) {
                        return false;
                    }

                }

            }
            else {
                return false;
            }
        }
        else {
            throw new Error("argunment is  error ;");
        }
        return true;
}

//nullObj

export const nullObj=function(obj){
    for(let key in obj){
        obj[key] = null;
    }
}

/*
*   cfg {
*      uploadUrl , 上传 路径
*      file, 文件或者数据
*      filename, 全路径文件名
*      code , 唯一编号，
*      readystatechange   ，callback
*      progress   ，callback
*      error ，
*      timeout
*   }
*

* */
export const upload = function(cfg){
    let xhr = new XMLHttpRequest();
    let form = new FormData(); // FormData 对象
    form.append('file',cfg.file);
    if(cfg.readystatechange){
        xhr.addEventListener('readystatechange',function(e){
            cfg.readystatechange(e,cfg);
        });
    }

    if(cfg.progress){
        xhr.addEventListener('progress',function(e){
            cfg.progress(e,cfg);
        });
    }

    if(cfg.error){
        xhr.addEventListener('error',function(e){
            cfg.error(e,cfg);
        });
    }

    if(cfg.timeout){
        xhr.addEventListener('timeout',function(e){
            cfg.timeout(e,cfg);
        });
    }
    xhr.open("POST", cfg.uploadUrl,true);
    xhr.send(form);

}

export const deleteArrayByCode=function(array,code){
    for(let i =0 ;i<array.length;i++){
        if(array[i].code == code){
            array.splice(i,1);
            break;
        }
    }
};

export const deepClone =function(obj){
    let objClone =  Array.isArray(obj) ? [] : {};
    if (obj && typeof obj === 'object') {
        for(let key in obj){
            if (obj[key] && typeof obj[key] === 'object'){
                objClone[key] = deepClone(obj[key]);
            }else{
                objClone[key] = obj[key]
            }
        }
    }
    return objClone;
};

export const getIconList= function(){

    let filePattern =/iconfont\.css$/;
    let classPattern = /^\.icon-[\w\d-]+/;

    let sheet ;
    for(let key in  document.styleSheets){
        if(filePattern.test(document.styleSheets[key].href)){
            sheet  = document.styleSheets[key];
            break;
        }
    }
    if(!sheet)
        return [];
    let list = [];
    for(let k in  sheet.rules){
        if(sheet.rules[k].selectorText){
            let match  = sheet.rules[k].selectorText.match(classPattern);
            if(match)
                list.push({icon:match[0].substr(1),code:match[0].substr(1),name:match[0].substr(1)});
        }
    }
    return list.sort( (a,b) => {return a.code>b.code; });
}


export const getTextContent = function(html){
    let div = document.createElement("div");
    div.innerHTML = html;
    let textContent = div.textContent;
    div.remove();
    return textContent;
}


export const getSumData = function(data,func,key,filter){
    let sum =0;
    let count =0;
    function match(item,filter){
        for(let key in filter){
            if (item[key] != filter[key])
                return false;
        }
        return true;
    }
    for(let d of data){
        if(filter){
            if(match(d,filter)){
                if(key)
                   sum += (d[key]-0);
                count += 1;
            }
        }else{
            if(key)
                sum += (d[key]-0);
            count += 1;
        }
    }

    switch(func){
        case 'sum':
            return sum;
        case 'count':
            return count;
        case 'avg':
            return  count==0?null:sum/count;
    }
};

/*  summernote 专用上传文件 */
export const sUploadImg =function(url,files,el) {
    let data = new FormData();
    data.append("file", files);
    $.ajax({
        data: data,
        dataType: 'json',
        type: "POST",
        url:url,
        cache: false,
        contentType: false,
        processData: false,
        responseType: "json",
        success: function (data) {
            $('#'+el).summernote('insertImage',data.filename);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest.status);
            alert(XMLHttpRequest.readyState);
            alert(textStatus);
        }
    });
}